<template>
  <!--  海报分享
  https://mp.weixin.qq.com/wxamp/devprofile/add_qrcode?prefix=https%3A%2F%2Fwechat.yytqb.com&token=1108878238&lang=zh_CN
  https://ext.dcloud.net.cn/plugin?id=2389
  -->
  <uni-popup ref="posterPopup" background-color="#fff" @change="posterPopupStatusChange">
    <view class="container">
      <image :src="path" mode="widthFix" :show-menu-by-longpress="true"></image>
      <l-painter
          :board="poster"
          isCanvasToTempFilePath
          @success="path = $event"
          hidden/>
    </view>

    <view class="address_nav_view">
      <view class="address_nav_box pos_f bgc_fff flex-aic flexr-jsc">
        <lyz-button @lyzTap="saveImage()" borderColor="#377851" backgroundColor="#377851" title="保存海报"></lyz-button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import {computed, reactive, ref, onMounted, watch} from "vue"
import {onLoad} from '@dcloudio/uni-app';
import {useStore} from "@/common/store";
// 以下路径需根据项目实际情况填写
import {pathToBase64, base64ToPath} from '@/common/utils/imageTools.js'
import {
  createUserBookingShareRecord,
  getPosterDetail,
  saveShareRecord
} from "@/common/api/xiaohesuan.js";

// 非ts写法
const props = defineProps({
  status: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(["closePoster"])

const posterPopup = ref(null)

const store = useStore();
const userId = computed(() => store.userId)
// 生成海报的 生成 true ,生成失败 false
const createPosterStatus = ref(true)
const posterId = ref('')
// 用户创建的编号
const ucsId = ref('')
// 生成的二维码图片base64
const path = ref('');
// 二维码设计页面顶部图片地址
const qrcodeTopImg = ref("")
// 二维码标签列表
const qrcodeTags = ref([{
  text: "祛斑，就去御研堂",
  type: "text",
  css: {
    color: "#235939",
    background: "#ffffff",
    marginRight: "34rpx",
    padding:"32rpx 0 16rpx 66rpx",
	fontSize: "34rpx",
	fontWeight:"600"
  },
}])

// 二维码描述信息
const qrcodeDesc = ref("御研堂生物祛斑")

// 二维码信息
const qrcodeURL = ref("https://wechat.yytqb.com?type=xhs&aa=1")

const poster = reactive({
  views: [{
    css: {
      // marginLeft: "40rpx",
      // marginTop: "30rpx",
      // padding: "32rpx",
      // boxSizing: "border-box",
      // background: "#fff",
      // borderRadius: "16rpx",
      // width: "570rpx",
      // boxShadow: "0 20rpx 58rpx rgba(0,0,0,.15)"
	  background: "#ffffff"
    },
    views: [{
      src: qrcodeTopImg,
      type: "image",
      css: {
        objectFit: "cover",
        objectPosition: "50% 50%",
        width: "570rpx",
        height: "609rpx",
		    background: "#ffffff"
		//图片上半部分格式
      },
    },
      {
        css: {
          // marginTop: "32rpx",
          // fontSize: "26rpx",
          // color: "#8c5400"
        },
        views: qrcodeTags,
        type: "view"
      }, {
        css: {
          // marginTop: "30rpx"
        },
        views: [
          {
            text: qrcodeDesc,
            type: "text",
            css: {
				      background: "#235939",
				      padding:"10rpx 27rpx 10rpx 27rpx",
              marginLeft: "66rpx",
              boxSizing: "border-box",
			        textAlign: "center",
              // lineClamp: 2,
              color: "#ffffff",
              fontSize: "36rpx",
              width: "280rpx",
			        borderRadius:"30rpx"
			        //扫码预约文字样式
            },
          }, {
            text: qrcodeURL,
            type: "qrcode",
            css: {
              width: "122rpx",
              height: "122rpx",
			        padding:"-55rpx 0 16rpx 66rpx"
			        //二维码
            },
          }],
        type: "view"
      }],
    type: "view"
  }
  ]
})

const posterToggle = () => {
  // open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
  posterPopup.value.open('center')
}

const saveImage = () => {
  base64ToPath(path.value).then((res) => {
    uni.saveImageToPhotosAlbum({
      filePath: res,
      success: function () {
        shareRecord();
        uni.showToast({
          icon: 'none',
          title: '保存成功'
        })
      }
    });
  }).catch((error) => {
    console.error(error);
  });
}

const createPosterTag = (tagText) => {
  return {
    text: tagText,
    type: "text",
    css: {
      color: "#212121",
      background: "#ffb400",
      marginRight: "16rpx"
    },
  }
}

const createPosterTages = (tags) => {
  const resTags = [];
  if (tags && tags.length > 0) {
    for (var i = 0; i < tags.length; i++) {
      resTags.push(createPosterTag(tags[i]));
    }
    qrcodeTags.value = resTags
    console.log(qrcodeTags)
  }
}

/**
 * 初始化海报信息
 */
const initPoster = async () => {
  await getPosterDetail().then(res => {
    createPosterStatus.value = true;
    qrcodeTopImg.value = res.backgroundUrl
    createPosterTages(res.posterTags)
    qrcodeDesc.value = res.posterDesc
    posterId.value = res.id
    let qrcu = res.qrcodeUrl;
    if (userId.value) {
      qrcu += '&shareUserId=' + userId.value + "&sharePosterId=" + res.id
    }
    qrcodeURL.value = qrcu
    console.log("poster")
    console.log(res)
  }).catch(reason => {
    createPosterStatus.value = false
  })
}

/**
 * 用户生成海报分享数据
 */
const createPostShareRecord = () => {
  if (userId.value) {
    const params = {
      userId: userId.value,
      shareUrl: qrcodeURL.value,
      qrcodeData: qrcodeURL.value,
      posterConfigId: posterId.value
    };
    createUserBookingShareRecord(params).then(res => {
      ucsId.value = res
    }).catch(reason => {
    })
  }
}

/**
 * 保存分享记录
 */
const shareRecord = () => {

  if (userId.value) {
    const params = {
      userId: userId.value,
      userCreateShareId: ucsId.value,
      posterConfigId: posterId.value
    };
    saveShareRecord(params).then(res => {
    }).catch(reason => {
      // uni.showToast({
      //   icon: 'none',
      //   title: '分享成功...'
      // })
    })
  }
}

const posterPopupStatusChange = (e) =>{
  if (e.show === false) {
    emit('closePoster', e);
  }
}

watch(
    () => props.status,
    (count, prevCount) => {
      if (props.status == true) {
        createPostShareRecord();
        posterPopup.value.open('center')
      }
    }
)

onLoad((options) => {
  console.log('接收传值：', options)
});

onMounted(() => {
  initPoster();
});

</script>

<style >
.container {
  width: 100%;
}
image{width: 567rpx; height: 767rpx;}
.address_nav_box{
  margin: 49rpx 120rpx 0 120rpx;
  padding:25rpx 103rpx 25rpx 103rpx;
  background-color: #377851;border-radius: 50rpx;
}
</style>
